#include <QtGui>

#include "vxtextitem.h"


VxTextItem::VxTextItem(QGraphicsItem *parent, QGraphicsScene *scene)
	: QGraphicsTextItem(parent, scene), _scene(scene), _thread(NULL)
{
	setFlag(QGraphicsItem::ItemIsSelectable, false);
}



QVariant VxTextItem::itemChange(GraphicsItemChange change,
                     const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedHasChanged)
        emit selectedChange(this);
    return value;
}



void VxTextItem::focusOutEvent(QFocusEvent *event)
{
    setTextInteractionFlags(Qt::NoTextInteraction);
    emit lostFocus(this);
    QGraphicsTextItem::focusOutEvent(event);
}



void VxTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    if (textInteractionFlags() == Qt::NoTextInteraction)
        setTextInteractionFlags(Qt::TextEditorInteraction);
    QGraphicsTextItem::mouseDoubleClickEvent(event);
}


void VxTextItem::keyPressEvent(QKeyEvent *event)
{
	if (event->key() == Qt::Key_Escape){
		if (textInteractionFlags() == Qt::TextEditorInteraction){
			setTextInteractionFlags(Qt::NoTextInteraction);
			setSelected(false);
		}
	}
	QGraphicsTextItem::keyPressEvent(event);
}


void VxTextItem::loadExample()
{
//	QString initialFile = ":/data/example1.txt";
/*	QString initialFile = ":/data/example.html";

	QFile file(initialFile);

	if (!file.open(QFile::ReadOnly))
		return;

	QByteArray data = file.readAll();
	QTextCodec *codec = Qt::codecForHtml(data);
	QString str = codec->toUnicode(data);


	if (Qt::mightBeRichText(str)) {
		this->setHtml(str);
	} else {
		str = QString::fromLocal8Bit(data);
		this->setPlainText(str);
	}
*/
	QString str("QWERTY");
	this->setPlainText(str);

	QFont font("Times", 24);
	font.setStyleStrategy(QFont::ForceOutline);
	this->setFont(font);

}

class GetOutLines : public QThread
{

	Q_OBJECT

public:
	GetOutLines(QObject *parent=0)
				: QThread(parent)
	{
		restart = false;
		abort = false;
	}

	~GetOutLines()
	{
		_mutex.lock();
		abort = true;
		_condition.wakeOne();
		_mutex.unlock();
		wait();
	}


	void render(QTextDocument * document)
	{
		QMutexLocker locker(&_mutex);

		_document = document;

		if (!isRunning()) {
			start(NormalPriority);
		} else {
			restart = true;
			_condition.wakeOne();
		}
	}

protected:


	void run(){

		forever {
			_mutex.lock();

			QTextCursor * tc = new QTextCursor(_document);

			_mutex.unlock();

			do{

				QRectF br = _document->documentLayout()->blockBoundingRect(tc->block());
				QFontMetrics fm(tc->charFormat().font());

				QString text = tc->block().text();
				qreal tx = br.left();
				qreal ty = br.bottom() - fm.descent() - 1;

				QString ktext;

				for(int i=0; i < text.length(); i++){
					QPainterPath * path = new QPainterPath();
					ktext +=  text.at(i);
					tx = fm.width(text, i) + br.left();
					path->addText(tx, ty, tc->charFormat().font(), text.at(i));

					emit outLineGenerate(path);

					if (restart){
						break;
					}
				}


			} while(tc->movePosition(QTextCursor::NextBlock)&&(!restart));

			delete tc;

			_mutex.lock();
			if (!restart)
				_condition.wait(&_mutex);

			restart = false;
			_mutex.unlock();

		}
	}

private:
	QMutex _mutex;
	QWaitCondition _condition;

	bool restart;
	bool abort;

	QTextDocument * _document;


signals:
	void outLineGenerate(QPainterPath*);

};


QGraphicsItem * VxTextItem::getOutLines(QGraphicsItemGroup * destinaion)
{
	if (_thread == NULL){

		_thread = new GetOutLines(this);
		connect(_thread, SIGNAL(outLineGenerate(QPainterPath*)), this,
							SLOT(_outLineGenerate(QPainterPath*)));
	}
	_destination = destinaion;

	_thread->render(this->document());

	return NULL;

}


void VxTextItem::_outLineGenerate(QPainterPath * path)
{
	QGraphicsPathItem * outline = new QGraphicsPathItem();

	outline->setPen(QPen(QColor(200,0,0, 180)));
	outline->setBrush(QBrush(QColor(0,0,0,220)));

	outline->setPath(*path);

	_destination->addToGroup(outline);
	outline->setFlag(QGraphicsItem::ItemIsMovable, true);
	outline->setFlag(QGraphicsItem::ItemIsSelectable, true);
}



void VxTextItem::_finishedThread()
{

}


#include "vxtextitem.moc"

